package cn.jtool.dig.server.comm.real;

import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.Session;
import cn.jtool.dig.common.netty.CtxUtils;
import cn.jtool.dig.common.netty.SessionManager;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@ChannelHandler.Sharable
public class RealOutHander extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        Packet packet = (Packet) msg;
        byte[] bytes = packet.getBody().getBytes();
        Long sessionId = CtxUtils.getAttribute(ctx, RealAttrKey.SESSION_ID);
        if(Objects.nonNull(sessionId)){
            Session session = SessionManager.getSession(sessionId);
            session.addSendByte(bytes.length);
            session.addTrafficBySegment(Session.TrafficDir.SEND, bytes.length);
        }
        super.write(ctx, Unpooled.wrappedBuffer(bytes), promise);
    }


}
